package com.kitchen
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	public class ClassLoader extends EventDispatcher
	{
		public static const LOADED_OK:String = 'LOADOK';
		public static const LOADED_ERROR:String = 'LOADERROR';
		
		private var loader:Loader;
		private var className:String;
		public var id:int;
		public var result:Class;
		
		public function ClassLoader(source:String, className:String, id:int=0)
		{
			this.className = className;
			this.id = id;
			this.loader = new Loader();
			this.loader.load(new URLRequest(source));
			this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedHandler);
			this.loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
		}
		
		private function loadedHandler(event:Event):void{
			this.result = this.loader.contentLoaderInfo.applicationDomain.getDefinition(this.className) as Class;
			this.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loadedHandler);
			this.loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			this.loader.unload();
			this.loader = null;
			this.dispatchEvent(new Event(LOADED_OK));
		}
		
		private function errorHandler(event:IOErrorEvent):void{
			this.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loadedHandler);
			this.loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			this.loader = null;
			this.dispatchEvent(new Event(LOADED_ERROR));
		}
	}
}